package com.flea.util;

import com.flea.def.Definition;
import com.flea.model.User;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SessionUtils {

    /**
     * <userId,httpSessionId>
     */
    private static Map<Integer, List<String>> userHttpSessionMap = new ConcurrentHashMap<>();

    private SessionUtils() {
    }

    public static User getSessionUser(HttpSession session) {
        return (User) session.getAttribute(Definition.USER_SESSION_KEY);
    }

    public static void addUserHttpSession(Integer userId, String httpSessionId) {
        List<String> httpSessionIdList = userHttpSessionMap.get(userId);
        if (httpSessionIdList == null) {
            httpSessionIdList = new ArrayList<>();
        }
        httpSessionIdList.add(httpSessionId);
        userHttpSessionMap.put(userId, httpSessionIdList);
    }

    public static void removeUserHttpSession(Integer userId) {
        userHttpSessionMap.remove(userId);
    }

    public static List<String> getHttpSessionId(Integer userId) {
        List<String> httpSessionIdList = userHttpSessionMap.get(userId);
        return httpSessionIdList == null ? Collections.emptyList() : httpSessionIdList;
    }

}
